package com.android.tea.api;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import com.android.tea.config.Config;
import com.android.tea.entity.Clientindustry;
import com.android.tea.entity.TeaCompany;
import com.android.tea.net.HttpResult;
import com.android.tea.net.HttpResultXml;
import com.android.tea.net.NetService;
import com.android.tea.shopper.ShopperActivity;
import com.android.tea.shopper.TeaClassInterface;
import com.android.tea.util.TeaLog;

/**
 * 用户相关api,包括注册和登录
 */
public class TeaApi extends BaseApi {

	private static final String TAG = "UserApi";

	public TeaApi(Context context) {
		super(context);
	}

	/**
	 * 获取分类
	 * 
	 * @param returnResultListener
	 * @param username
	 * @param password
	 */
	public void getTeaSort(final int requestCode) {
		new AsyncTask<Object, Integer, ApiResult<Object>>() {
			@Override
			protected ApiResult<Object> doInBackground(Object... strs) {
				ApiResult<Object> apiResult = new ApiResult<Object>();
				apiResult.setResultCode(ApiResult.RESULT_FAIL);

				HttpResultXml result = NetService.httpGetReturnXml(context,
						Config.TEA_SORT_URL, null);

				HashMap<String, Clientindustry> map = null;

				if (result.getResultCode() == HttpResult.RESULT_OK) {
					apiResult.setResultCode(ApiResult.RESULT_OK);

					HashMap<String, Clientindustry> tempFatherList = new HashMap<String, Clientindustry>();

					XmlPullParser parser = result.getParser();

					try {
						int eventType = parser.getEventType();
						map = new HashMap<String, Clientindustry>();
						Clientindustry industry = null;
						while (eventType != XmlPullParser.END_DOCUMENT) {
							String nodeName = parser.getName();
							switch (eventType) {
							case XmlPullParser.START_DOCUMENT:
								break;
							case XmlPullParser.START_TAG:

								if (nodeName.equalsIgnoreCase("eBook")) {
									industry = new Clientindustry();
								} else if (nodeName.equalsIgnoreCase("coinId")) {
									industry.setCoinId(parser.nextText());
								} else if (nodeName
										.equalsIgnoreCase("coinName")) {
									industry.setCoinName(parser.nextText());
								} else if (nodeName
										.equalsIgnoreCase("coinParentId")) {
									industry.setParentId(parser.nextText());
								}

								break;
							case XmlPullParser.END_TAG:
								if (nodeName.equalsIgnoreCase("eBook")) {
									if (industry != null) {
										map.put(industry.getCoinId(), industry);
									}
								}
								break;
							case XmlPullParser.END_DOCUMENT:
								break;
							}
							eventType = parser.next();
						}
					} catch (XmlPullParserException e) {
						TeaLog.e(TAG, e);
					} catch (IOException e) {
						TeaLog.e(TAG, e);
					}

					TeaLog.e(TAG, "map size is " + map.size());

					Clientindustry industry = new Clientindustry();
					industry.setMap(map);
					apiResult.setEntity(industry);

				} else {
					apiResult.setFailCode(result.getFailCode());
					apiResult.setFailMessage(result.getFailMessage());
				}
				return apiResult;
			}

			@Override
			protected void onPostExecute(ApiResult<Object> apiResult) {
				if (returnResultListener == null) {
					return;
				}
				if (apiResult.getResultCode() == ApiResult.RESULT_OK) {
					returnResultListener.onReturnSucceedResult(requestCode,
							apiResult);
				} else {
					returnResultListener.onReturnFailResult(requestCode,
							apiResult);
				}
			}
		}.execute("");
	}

	/**
	 * 推荐列表
	 * 
	 * @param requestCode
	 */
	public void getTeaRecommends(final int requestCode, final String location,
			final String range, final String coinId, final String offer) {
		new AsyncTask<Object, Integer, ApiResult<Object>>() {
			@Override
			protected ApiResult<Object> doInBackground(Object... strs) {
				ApiResult<Object> apiResult = new ApiResult<Object>();
				apiResult.setResultCode(ApiResult.RESULT_FAIL);

				// String param = "?companyMap=" + location + "&" + "range=" +
				// range + "&coinIds=" + coinId + "&offer=" + offer;
				// TeaLog.e(TAG,"param is " + param);
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				if (location != null)
					params.add(new BasicNameValuePair("companyMap", location
							.trim()));
				if (range != null)
					params.add(new BasicNameValuePair("range", range.trim()));
				if (coinId != null) {
					params
							.add(new BasicNameValuePair("coinIds", coinId
									.trim()));
				}
				if (offer != null) {
					params.add(new BasicNameValuePair("offer", offer));
				}
				// List<NameValuePair> params = new ArrayList<NameValuePair>();
				// params.add(new BasicNameValuePair("companyMap",
				// "116.3,39.9"));
				// params.add(new BasicNameValuePair("range", "150"));
				// params.add(new BasicNameValuePair("coinIds",
				// "343982f03c222eb8013c2284d51b0002"));
				// params.add(new BasicNameValuePair("offer", "0,50"));

				// HttpResultXml result = NetService.httpPostReturnXml(context,
				// Config.TEA_RECOMMEND_URL, null);
				HttpResultXml result = NetService.httpGetReturnXml(context,
						Config.TEA_RECOMMEND_URL, params);

				ArrayList<TeaCompany> list = null;
				if (result.getResultCode() == HttpResult.RESULT_OK) {
					apiResult.setResultCode(ApiResult.RESULT_OK);

					XmlPullParser parser = result.getParser();
					try {
						int eventType = parser.getEventType();
						list = new ArrayList<TeaCompany>();
						TeaCompany company = null;
						while (eventType != XmlPullParser.END_DOCUMENT) {
							String nodeName = parser.getName();
							switch (eventType) {
							case XmlPullParser.START_DOCUMENT:
								break;
							case XmlPullParser.START_TAG:

								if (nodeName.equalsIgnoreCase("eBook")) {
									company = new TeaCompany();
								} else if (nodeName.equalsIgnoreCase("coinId")) {
									company.setCoinId(parser.nextText());
								} else if (nodeName
										.equalsIgnoreCase("companyId")) {
									company.setCompanyId(parser.nextText());
								} else if (nodeName
										.equalsIgnoreCase("companyName")) {
									company.setCompanyName(parser.nextText());
								} else if (nodeName
										.equalsIgnoreCase("companyLogo")) {
									company.setCompanyLogo(parser.nextText());
								} else if (nodeName
										.equalsIgnoreCase("coinName")) {
									company.setCoinName(parser.nextText());
								} else if (nodeName
										.equalsIgnoreCase("companyCityCode")) {
									company.setCompanyCityCode(parser
											.nextText());
								} else if (nodeName
										.equalsIgnoreCase("companyTel")) {
									company.setCompanyTel(parser.nextText());
								} else if (nodeName
										.equalsIgnoreCase("companyEmail")) {
									company.setCompanyEmail(parser.nextText());
								} else if (nodeName
										.equalsIgnoreCase("companyCaco")) {
									company.setCompanyCaco(parser.nextText());
								} else if (nodeName
										.equalsIgnoreCase("companyMap")) {
									company.setCompanyMap(parser.nextText());
								}

								break;
							case XmlPullParser.END_TAG:
								if (nodeName.equalsIgnoreCase("eBook")) {
									list.add(company);
								}
								break;
							case XmlPullParser.END_DOCUMENT:
								break;
							}
							eventType = parser.next();
						}
					} catch (XmlPullParserException e) {
						TeaLog.e(TAG, e);
					} catch (IOException e) {
						TeaLog.e(TAG, e);
					}
					TeaLog.e(TAG, "茶系推荐   list size is " + list.size());
					apiResult.setList(list);

				} else {
					apiResult.setFailCode(result.getFailCode());
					apiResult.setFailMessage(result.getFailMessage());
				}
				return apiResult;
			}

			@Override
			protected void onPostExecute(ApiResult<Object> apiResult) {
				if (returnResultListener == null) {
					return;
				}
				if (apiResult.getResultCode() == ApiResult.RESULT_OK) {
					returnResultListener.onReturnSucceedResult(requestCode,
							apiResult);
				} else {
					returnResultListener.onReturnFailResult(requestCode,
							apiResult);
				}
			}
		}.execute("");
	}

	/**
	 * 商家详情
	 * 
	 * @param requestCode
	 */
	public void getTeaDetail(final int requestCode, final String companyid) {// TODO
		// 接口不能用
		new AsyncTask<Object, Integer, ApiResult<Object>>() {
			@Override
			protected ApiResult<Object> doInBackground(Object... strs) {
				ApiResult<Object> apiResult = new ApiResult<Object>();
				apiResult.setResultCode(ApiResult.RESULT_FAIL);

				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("id", companyid.trim()));

				HttpResultXml result = NetService.httpGetReturnXml(context,
						Config.TEA_DETAIL_URL, params);
				if (result.getResultCode() == HttpResult.RESULT_OK) {
					apiResult.setResultCode(ApiResult.RESULT_OK);

					XmlPullParser parser = result.getParser();
					try {
						int eventType = parser.getEventType();
						TeaCompany company = null;
						while (eventType != XmlPullParser.END_DOCUMENT) {
							String nodeName = parser.getName();
							switch (eventType) {
							case XmlPullParser.START_DOCUMENT:
								break;
							case XmlPullParser.START_TAG:

								if (nodeName.equalsIgnoreCase("eBook")) {
									company = new TeaCompany();
								} else if (nodeName
										.equalsIgnoreCase("companyName")) {
									company.setCompanyName(parser.nextText());
								} else if (nodeName
										.equalsIgnoreCase("companyLogo")) {
									company.setCompanyLogo(parser.nextText());
								} else if (nodeName
										.equalsIgnoreCase("coinName")) {
									company.setCoinName(parser.nextText());
								} else if (nodeName
										.equalsIgnoreCase("cogeName")) {
									company.setCompanyCaco(parser.nextText());
								} else if (nodeName
										.equalsIgnoreCase("companyIntroduce")) {
									company.setCompanyDesc(parser.nextText());
								} else if (nodeName
										.equalsIgnoreCase("companyImages")) {
									company.setCompanyImages(parser.nextText());
								} else if (nodeName
										.equalsIgnoreCase("companyCityCode")) {
									company.setCompanyCityCode(parser
											.nextText());
								}

								break;
							case XmlPullParser.END_TAG:
								if (nodeName.equalsIgnoreCase("eBook")) {
									TeaLog.e(TAG, "company name is "
											+ company.getCoinName());
									apiResult.setEntity(company);
								}
								break;
							case XmlPullParser.END_DOCUMENT:
								break;
							}
							eventType = parser.next();
						}
					} catch (XmlPullParserException e) {
						TeaLog.e(TAG, e);
					} catch (IOException e) {
						TeaLog.e(TAG, e);
					}

				} else {
					apiResult.setFailCode(result.getFailCode());
					apiResult.setFailMessage(result.getFailMessage());
				}
				return apiResult;
			}

			@Override
			protected void onPostExecute(ApiResult<Object> apiResult) {
				if (returnResultListener == null) {
					return;
				}
				if (apiResult.getResultCode() == ApiResult.RESULT_OK) {
					returnResultListener.onReturnSucceedResult(requestCode,
							apiResult);
				} else {
					returnResultListener.onReturnFailResult(requestCode,
							apiResult);
				}
			}
		}.execute("");
	}

	/**
	 * 添加商家
	 * 
	 * @param requestCode
	 */
	public void addTeaShop(final int requestCode, final TeaCompany company) {// TODO
		// 该接口不能用
		new AsyncTask<Object, Integer, ApiResult<Object>>() {
			@Override
			protected ApiResult<Object> doInBackground(Object... strs) {
				ApiResult<Object> apiResult = new ApiResult<Object>();
				apiResult.setResultCode(ApiResult.RESULT_FAIL);

				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("company.companyName",
						company.getCompanyName()));
				params.add(new BasicNameValuePair("company.coinIds", company
						.getCoinId()));
				params.add(new BasicNameValuePair("company.companyAddress",
						company.getCompanyCityCode()));
				params.add(new BasicNameValuePair("company.companyTel", company
						.getCompanyTel()));
				params.add(new BasicNameValuePair("company.companyEmail",
						company.getCompanyEmail()));
				params.add(new BasicNameValuePair("company.companyCaco",
						company.getCompanyCaco()));
				params.add(new BasicNameValuePair("company.companyMap", company
						.getCompanyMap()));
				params.add(new BasicNameValuePair("memberId", "2"));

				HttpResultXml result = NetService.httpPostReturnString(context,
						Config.TEA_ADD_URL, params);

				if (result.getResultCode() == HttpResult.RESULT_OK) {
					apiResult.setResultCode(ApiResult.RESULT_OK);
					String resultMsg = result.getResultMsg();
					apiResult.setResultMsg(resultMsg);
				} else {
					apiResult.setFailCode(result.getFailCode());
					apiResult.setFailMessage(result.getFailMessage());
				}
				return apiResult;
			}

			@Override
			protected void onPostExecute(ApiResult<Object> apiResult) {
				if (returnResultListener == null) {
					return;
				}
				if (apiResult.getResultCode() == ApiResult.RESULT_OK) {
					returnResultListener.onReturnSucceedResult(requestCode,
							apiResult);
				} else {
					returnResultListener.onReturnFailResult(requestCode,
							apiResult);
				}
			}
		}.execute("");
	}

	public static ArrayList<Clientindustry> teaClass = null;
	public static boolean isGettingClass = false;

	public static void getTeaClass(Context context, final TeaClassInterface i) {

		if (isGettingClass) {
			return;
		}
		if (teaClass == null) {
			final ProgressDialog myDialog;
			myDialog = ProgressDialog.show(ShopperActivity.instance, "请稍候",
					"正在获取茶系列表", true);
			myDialog.setCancelable(true);
			isGettingClass = true;
			TeaApi teaApi = new TeaApi(context);
			teaApi.getTeaList(0);
			teaApi.setReturnResultListener(new ApiReturnResultListener() {
				@Override
				public <T> void onReturnSucceedResult(int requestCode,
						ApiResult<T> apiResult) {
					isGettingClass = false;
					teaClass = (ArrayList<Clientindustry>) apiResult.getList();
					i.callbackTeaClass(teaClass);
					myDialog.dismiss();
				}

				@Override
				public <T> void onReturnFailResult(int requestCode,
						ApiResult<T> apiResult) {
					isGettingClass = false;
					i.callbackTeaClass(null);
					myDialog.dismiss();
				}
			});
		} else {
			i.callbackTeaClass(teaClass);
		}

	}

	/**
	 * 茶系列表
	 * 
	 * @param requestCode
	 */
	public void getTeaList(final int requestCode) {
		new AsyncTask<Object, Integer, ApiResult<Object>>() {
			@Override
			protected ApiResult<Object> doInBackground(Object... strs) {
				ApiResult<Object> apiResult = new ApiResult<Object>();
				apiResult.setResultCode(ApiResult.RESULT_FAIL);

				HttpResultXml result = NetService.httpGetReturnXml(context,
						Config.TEA_LIST_URL, null);
				ArrayList<Clientindustry> list = null;
				if (result.getResultCode() == HttpResult.RESULT_OK) {
					apiResult.setResultCode(ApiResult.RESULT_OK);

					XmlPullParser parser = result.getParser();
					try {
						int eventType = parser.getEventType();
						list = new ArrayList<Clientindustry>();
						Clientindustry industry = null;
						while (eventType != XmlPullParser.END_DOCUMENT) {
							String nodeName = parser.getName();
							switch (eventType) {
							case XmlPullParser.START_DOCUMENT:
								break;
							case XmlPullParser.START_TAG:

								if (nodeName.equalsIgnoreCase("eBook")) {
									industry = new Clientindustry();
								} else if (nodeName
										.equalsIgnoreCase("comaprId")) {
									industry.setCoinId(parser.nextText());
								} else if (nodeName
										.equalsIgnoreCase("comaprName")) {
									industry.setCoinName(parser.nextText());
								}

								break;
							case XmlPullParser.END_TAG:
								if (nodeName.equalsIgnoreCase("eBook")) {
									list.add(industry);
								}
								break;
							case XmlPullParser.END_DOCUMENT:
								break;
							}
							eventType = parser.next();
						}
					} catch (XmlPullParserException e) {
						TeaLog.e(TAG, e);
					} catch (IOException e) {
						TeaLog.e(TAG, e);
					}
					TeaLog.e(TAG, "茶系列表   map size is " + list.size());
					apiResult.setList(list);

				} else {
					apiResult.setFailCode(result.getFailCode());
					apiResult.setFailMessage(result.getFailMessage());
				}
				return apiResult;
			}

			@Override
			protected void onPostExecute(ApiResult<Object> apiResult) {
				if (returnResultListener == null) {
					return;
				}
				if (apiResult.getResultCode() == ApiResult.RESULT_OK) {
					returnResultListener.onReturnSucceedResult(requestCode,
							apiResult);
				} else {
					returnResultListener.onReturnFailResult(requestCode,
							apiResult);
				}
			}
		}.execute("");
	}

	public void feedBack(final int requestCode, final String content,
			final String username, final String telephone) {
		new AsyncTask<Object, Integer, ApiResult<Object>>() {
			@Override
			protected ApiResult<Object> doInBackground(Object... strs) {
				ApiResult<Object> apiResult = new ApiResult<Object>();
				apiResult.setResultCode(ApiResult.RESULT_FAIL);
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("m", "guestbook"));
				params.add(new BasicNameValuePair("c", "index"));
				params.add(new BasicNameValuePair("a", "back"));
				params.add(new BasicNameValuePair("name", username.trim()));
				params.add(new BasicNameValuePair("tel", telephone.trim()));
				params.add(new BasicNameValuePair("introduce", content.trim()));

				HttpResultXml result = NetService.httpGetReturnString(context,
						Config.TEA_FEEDBACK_URL, params);
				if (result.getResultCode() == HttpResult.RESULT_OK) {
					apiResult.setResultCode(ApiResult.RESULT_OK);
					String resultMsg = result.getResultMsg();
					apiResult.setResultMsg(resultMsg);
				} else {
					apiResult.setFailCode(result.getFailCode());
					apiResult.setFailMessage(result.getFailMessage());
				}
				return apiResult;
			}

			@Override
			protected void onPostExecute(ApiResult<Object> apiResult) {
				if (returnResultListener == null) {
					return;
				}
				if (apiResult.getResultCode() == ApiResult.RESULT_OK) {
					returnResultListener.onReturnSucceedResult(requestCode,
							apiResult);
				} else {
					returnResultListener.onReturnFailResult(requestCode,
							apiResult);
				}
			}
		}.execute("");
	}
}
